<template>
	<view class="u-page">
		<!-- 下拉刷新容器 -->
		<scroll-view
			scroll-y
			class="uni-list"
			refresher-enabled
			:refresher-triggered="loadType === 'refresh'"
			:style="{ height: listHeight }"
			@refresherrefresh="refresh"
			@scrolltolower="loadMore"
		>
			<uni-list>
				<uni-list-item 
					v-for="(item, index) in listData" 
					:key="index"
					:title="`${item.order_sn}|${item.type_id[0]?.text||'汽车服务'}`"
					:note="`车管家：${item.butler_id[0]?.text||'无'}`"
					:rightText="`${options.status_valuetotext[item.status]}`"
					:showArrow="true"
					:ellipsis="1"
					:badgeText="item.score===1?'介入':''"
					:badgeType="item.score===1?'error':''"
					:showBadge="item.score===1"
					badge-positon="left"
					clickable
					@click="handleItemClick(item._id,item.status)"
					:class="item.score===1?'error-item':''"
				>
				</uni-list-item>
			</uni-list>
			
			<!-- 加载状态 -->
			<uni-load-state 
				@networkResume="refresh"
				:state="{ data: listData, pagination: { current: page, pageSize: pageSize }, hasMore: loadStatus === 'more', loading: loadStatus === 'loading', error: null }"
				@loadMore="loadMore"
			>
			</uni-load-state>
		</scroll-view>
	</view>
</template>

<script>
	import {
		enumConverter
	} from '../../js_sdk/validator/yycw_car_service_order.js'
	const db = uniCloud.database()
	const userInfo = uniCloud.getCurrentUserInfo()

	export default {
		data() {
			return {
				where: `user_id==${userInfo.uid}`,
				options: {
					// 将scheme enum 属性静态数据中的value转成text
					...enumConverter
				},
				page: 1,
				pageSize: 15,
				total: 0,
				loadStatus: 'noMore', // more | loading | noMore
				listData: [],
				listHeight: 0, // 列表高度
				loadType: null // 加载类型：refresh | loadMore
			}
		},
		onLoad(options) {
			if (options.role && !this.uniIDHasRole(options.role)) {
				//无权限访问页面
				uni.showToast({
					icon: 'none',
					title: '无权限访问',
				})
				setTimeout(() => uni.navigateBack(), 1000)
				return
			}
			// console.debug('role:'+ options.role)
			this.role = options.role
			//默认加载车管家服务工单列表
			if ('butler' === options.role) {
				this.where = `("butler_id"=="${userInfo.uid}" || "help_butler_id"=="${userInfo.uid}") && status>=1`
			} else if ('auditor' === options.role) {
				uni.setNavigationBarTitle({
					title: '服务工单(初审)' // 最多支持 6 个汉字
				})
				this.where = 'status>=0'
			} else if ('supervisor' === options.role) {
				uni.setNavigationBarTitle({
					title: '服务工单(稽核)' // 最多支持 6 个汉字
				})
				this.where = `status>=1`
			} else if ('officer' === options.role) {
				uni.setNavigationBarTitle({
					title: '服务工单(财务)' // 最多支持 6 个汉字
				})
				this.where = `status>=4`
			} else {
				uni.setNavigationBarTitle({
					title: '派单历史' // 最多支持 6 个汉字
				})
				this.where = `user_id=="${userInfo.uid}"`
			}

			this.initListHeight()
			this.loadData()
		},
		onPullDownRefresh() {
			this.refresh()
		},
		onReachBottom() {
			this.loadMore()
		},
		methods: {
			// 初始化列表高度
			initListHeight() {
				// 获取系统信息
				const systemInfo = uni.getSystemInfoSync()
				// 计算列表高度：窗口高度 - 状态栏高度 - 导航栏高度
				this.listHeight = (systemInfo.windowHeight - systemInfo.statusBarHeight - 44) + 'px'
			},
			
			async loadData() {
				try {
					this.loadStatus = 'loading'
					const orderTemp = db.collection('yycw_car_service_order').where(this.where)
						.field('order_sn,type_id,user_id,butler_id,status,score,create_date').getTemp()
					const typeTemp = db.collection('yycw_car_service_type').field('service_name as text, _id').getTemp()
					const userTemp = db.collection('uni-id-users').field('nickname as text, _id').getTemp()
					//编号|用户|服务项目|				状态，是否介入，优秀
					//车管家  xxx  时间 xxx
					const res = await db.collection(orderTemp, typeTemp, userTemp)
						.skip((this.page - 1) * this.pageSize)
						.limit(this.pageSize)
						.get()
					
					this.total = res.result.total
					
					// 根据加载类型处理数据
					if (this.loadType === 'loadMore') {
						this.listData = [...this.listData, ...res.result.data]
					} else {
						this.listData = res.result.data
					}
					
					// 更新加载状态
					this.loadStatus = res.result.data.length < this.pageSize ? 'noMore' : 'more'
					
				} catch (error) {
					console.error('加载数据失败:', error)
					this.loadStatus = 'noMore'
					uni.showToast({
						icon: 'none',
						title: '加载失败，请重试'
					})
				} finally {
					this.loadType = null
				}
			},
			
			// 下拉刷新
			refresh() {
				this.loadType = 'refresh'
				this.page = 1
				this.loadData().finally(() => {
					uni.stopPullDownRefresh()
				})
			},
			
			// 上拉加载更多
			loadMore() {
				if (this.loadStatus === 'more' && this.loadType !== 'loadMore') {
					this.loadType = 'loadMore'
					this.page++
					this.loadData()
				}
			},
			
			// 重试加载
			retry() {
				this.refresh()
			},
			
			handleItemClick(id, status) {
				// if(paymant_status || paymant_status == 0){
				if (this.role == 'auditor' && status == 0) {
					uni.navigateTo({
						url: './auditor?id=' + id
					})
					return
				} 
				// else if ((['butler', 'officer'].includes(this.role) && status <= 3) || 'supervisor' === this.role) {
				// 	uni.navigateTo({
				// 		url: `./service?id=${id}&role=${this.role}`
				// 	})
				// 	return
				// } 
				else if (['butler', 'officer', 'supervisor'].includes(this.role) ) {
					uni.navigateTo({
						url: `./service?id=${id}&role=${this.role}`
					})
					return
				} else{
					uni.navigateTo({
						url: './detail?id=' + id
					})
				}
			}
		}
	}
</script>

<style lang="scss">
	.u-page {
		background-color: #FFFFFF;
	}
	
	.uni-list {
		/* #ifndef APP-NVUE */
		display: flex;
		box-sizing: border-box;
		flex-direction: column;
		/* #endif */
	}
	
	// 介入状态的错误样式
	.uni-list-item {
		&.error-item {
			background-color: #fff5f5 !important;
			border-left: 4px solid #ff0000 !important;
			
			.uni-list-item__content-title {
				color: #ff0000 !important;
				font-weight: bold;
			}
			
			.uni-list-item__content-note {
				color: #ff6b6b !important;
			}
			
			.uni-list-item__extra-text {
				color: #ff0000 !important;
				font-weight: bold;
			}
		}
	}
</style>